//定制请求的实例

//导入axios  npm install axios
import axios from 'axios';
//elementPlus弹消息
import { ElMessage } from 'element-plus'
//定义一个变量,记录公共的前缀  ,  baseURL
//const baseURL = '/api';
const baseURL = '/api';
const instance = axios.create({ baseURL })


import { useTokenStore } from '@/stores/token.js'
import router from '@/router';

//添加请求拦截器
instance.interceptors.request.use(
    config => {
        //请求前的回调
        //添加token
        const tokenStore = useTokenStore()
        if (tokenStore.token) {
            config.headers.authentication = tokenStore.token
        }
        return config
    },
    err => {
        Promise.reject();
    }
)
//添加响应拦截器
instance.interceptors.response.use(
    result => {
        //成功，返回数据
        if (result.data.code === 1) {
            return result.data;
        }
        //失败
        ElMessage.error(result.data.msg ? result.data.msg : '服务异常')
        console.log(result.data);
        //异步的状态转化成失败的状态
        return Promise.reject(result.data)
    },
    err => {
        if (err.response.status === 401) {
            ElMessage.error('请先登录')
            router.push('/login')
        } else {
            ElMessage.error(err.data.msg ? err.data.msg : '服务异常')
        }
        return Promise.reject(err);//异步的状态转化成失败的状态
    }
)

export default instance;